package dao;

import java.sql.*;

public class BaseDao {
    public Connection conn=null;
    public PreparedStatement pstm=null;
    public ResultSet rs=null;

    /**
     *  数据源配置
     *
     * @return
     */
    public Connection getConn(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/pet?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8","root","123456");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 查询方法
     *
     * @param sql
     * @param param
     * @return
     */
    public ResultSet query(String sql,Object[] param){
        conn=getConn();
        try {
            pstm=conn.prepareStatement(sql);
            if (param!=null){
                for (int i = 0; i <param.length ; i++) {
                    pstm.setObject(i+1,param[i]);
                }
            }
            rs=pstm.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }

    /**
     *  增删改
     *
     * @param sql
     * @param param
     * @return
     */
    public int execute(String sql,Object[] param){
        int rows=0;
        conn=getConn();
        try {
            pstm=conn.prepareStatement(sql);
            if (param!=null){
                for (int i = 0; i <param.length ; i++) {
                    pstm.setObject(i+1,param[i]);
                }
            }
            rows = pstm.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return rows;
    }

    /**
     *  关闭资源
     *
     * @param conn
     * @param pstm
     * @param rs
     */
    public void closeAll(Connection conn,PreparedStatement pstm,ResultSet rs){
        try {
            if (rs!=null) {
                rs.close();
            }
            if (pstm!=null){
                pstm.close();
            }
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
                e.printStackTrace();
        }
    }
}
